package log

import (
	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"io"
	"os"
	"time"
)

var Logger *zap.Logger
var SugarLogger *zap.SugaredLogger

//var logPath = "./.log/info.log"
//var errPath = "./.log/error.log"

func init() {
	encoderConfig := zapcore.EncoderConfig{
		TimeKey:       "time",
		LevelKey:      "level",
		NameKey:       "logger",
		CallerKey:     "caller",
		MessageKey:    "msg",
		StacktraceKey: "stacktrace",
		LineEnding:    zapcore.DefaultLineEnding,
		EncodeLevel:   zapcore.CapitalLevelEncoder,
		EncodeTime: func(time time.Time, encoder zapcore.PrimitiveArrayEncoder) {
			encoder.AppendString(time.Format("2006-01-02 15:04:05"))
		},
		EncodeDuration: zapcore.SecondsDurationEncoder,
		EncodeCaller:   zapcore.ShortCallerEncoder,
	}
	//config := zap.Config{
	//	Level:         zap.NewAtomicLevelAt(zap.InfoLevel), // 日志级别
	//	Development:   true,                                // 开发模式，堆栈跟踪
	//	Encoding:      "console",                           // 输出格式 console 或 json
	//	EncoderConfig: encoderConfig,                       // 编码器配置
	//	OutputPaths:      []string{"stdout"}, // 输出到指定文件 stdout（标准输出，正常颜色） stderr（错误输出，红色）
	//	ErrorOutputPaths: []string{"stderr"},
	//}

	//infoWriter := getWriter(logPath)
	//warnWriter := getWriter(errPath)

	core := zapcore.NewTee(
		//zapcore.NewCore(zapcore.NewConsoleEncoder(encoderConfig), zapcore.AddSync(infoWriter), zapcore.InfoLevel),
		//zapcore.NewCore(zapcore.NewConsoleEncoder(encoderConfig), zapcore.AddSync(warnWriter), zapcore.WarnLevel),
		zapcore.NewCore(zapcore.NewConsoleEncoder(encoderConfig), zapcore.AddSync(os.Stdout), zapcore.InfoLevel),
		zapcore.NewCore(zapcore.NewConsoleEncoder(encoderConfig), zapcore.AddSync(os.Stderr), zapcore.WarnLevel),
	)
	Logger = zap.New(core, zap.AddCaller(), zap.AddStacktrace(zap.WarnLevel))
	SugarLogger = Logger.Sugar()
}

func getWriter(filename string) io.Writer {
	return &lumberjack.Logger{
		Filename:   filename,
		MaxSize:    10,    //最大M数，超过则切割
		MaxBackups: 5,     //最大文件保留数，超过就删除最老的日志文件
		MaxAge:     30,    //保存30天
		Compress:   false, //是否压缩
	}
}
